package com.app.controller.importExcel;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;


/**
 * 导入实验任务excel
 */
@Slf4j
@RestController
@Controller
@RequestMapping("/api/import")
public class ImportTestTaskController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TestFailureService testFailureService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private TestsRecordService testsRecordService;

    @Autowired
    private ProtectionPointService protectionPointService;

    // 导入实验故障统计excel文件
    @PostMapping("/importTestFailure")
    public Result<Object> importTestFailure(MultipartFile file, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "number");
        reader.addHeaderAlias("装备型号", "equipModel");
        reader.addHeaderAlias("任务名称", "taskName");
        reader.addHeaderAlias("所属单位", "departmentName");
        reader.addHeaderAlias("问题时间", "questionTime");
        reader.addHeaderAlias("问题名称", "questionName");
        reader.addHeaderAlias("问题现象", "questionPhenomenon");
        reader.addHeaderAlias("问题原因", "questionCause");
        reader.addHeaderAlias("问题等级", "questionGrade");
        reader.addHeaderAlias("问题类型", "questionModel");
        reader.addHeaderAlias("解决进度", "resolutionProgress");
        reader.addHeaderAlias("需要机关协调解决", "isUseText");
        reader.addHeaderAlias("备注", "remark");
        //reader.read(标头行数，开始行数，对象)
        List<TestFailureModel> testFailureModels = reader.read(0, 1, TestFailureModel.class);
        for (int i = 0; i < testFailureModels.size(); i++) {
            TestFailureModel testFailureModel = testFailureModels.get(i);
            DepartmentModel departmentModel = departmentService.getdepByName(testFailureModel.getDepartmentName());
            if (departmentModel != null) {
                testFailureModel.setDepartmentId(departmentModel.getId());
//                int row = i + 3;
//                return Result.error(500, "第" + row + "行单位不存在");
            }
            if (testFailureModel.getIsUseText() != null && testFailureModel.getIsUseText().equals("是")) {
                testFailureModel.setIsUse(1);
            } else {
                testFailureModel.setIsUse(0);
            }

            testFailureModel.setCreateTime(CommonHelp.getNowTimestamp());
            try {
                testFailureService.insert(testFailureModel);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500,"导入失败");
            }
        }
        return Result.success("");
    }


    // 导入实验记录统计excel文件
    @PostMapping("/importTestRecord")
    public Result<Object> importTestRecord(MultipartFile file, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("年度", "year");
        reader.addHeaderAlias("型号", "modelUnit");
        reader.addHeaderAlias("所属单位", "departmentName");
        reader.addHeaderAlias("试验日期", "testTime");
        reader.addHeaderAlias("试验类型", "testType");
        reader.addHeaderAlias("试验科目", "testSubject");
        reader.addHeaderAlias("问题原因", "testCondition");
        reader.addHeaderAlias("试验结果", "testResult");
        reader.addHeaderAlias("出现故障", "testFault");
        reader.addHeaderAlias("故障分析定位", "testFaultAnalysis");
        reader.addHeaderAlias("解决方式", "faultSolution");
        reader.addHeaderAlias("归零评审日期", "reviewTime");
        reader.addHeaderAlias("遗留问题", "remainingProblems");
        reader.addHeaderAlias("改进意见建议", "recommendation");
        //reader.read(标头行数，开始行数，对象)
        List<TestsRecordModel> testsRecordModels = reader.read(1, 2, TestsRecordModel.class);
        for (int i = 0; i < testsRecordModels.size(); i++) {
            TestsRecordModel testsRecordModel = testsRecordModels.get(i);
            DepartmentModel departmentModel = departmentService.getdepByName(testsRecordModel.getDepartmentName());
            if (departmentModel != null) {
                testsRecordModel.setDepartmentId(departmentModel.getId());
//                int row = i + 3;
//                return Result.error(500, "第" + row + "行单位不存在");
            }

            testsRecordModel.setCrtTime(CommonHelp.getNowTimestamp());
            try {
                testsRecordService.insert(testsRecordModel);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500,"导入失败");
            }
        }
        return Result.success("");
    }

    // 导入保护点.信息导入
    @PostMapping("/importProtectionPoint")
    public Result<Object> importProtectionPoint(MultipartFile file, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "number");
        reader.addHeaderAlias("名称", "name");
        reader.addHeaderAlias("经度", "longitude");
        reader.addHeaderAlias("纬度", "latitude");
        reader.addHeaderAlias("保护半径", "radius");
        reader.addHeaderAlias("隶属", "departmentName");
        reader.addHeaderAlias("联系方式", "contactInformation");
        reader.addHeaderAlias("备注", "remark");
        //reader.read(标头行数，开始行数，对象)
        List<ProtectionPointModel> protectionPointModels = reader.read(0, 0, ProtectionPointModel.class);
        for (int i = 0; i < protectionPointModels.size(); i++) {
            ProtectionPointModel protectionPointModel = protectionPointModels.get(i);
            DepartmentModel departmentModel = departmentService.getdepByName(protectionPointModel.getDepartmentName());
            if (departmentModel != null) {
                protectionPointModel.setDepartmentId(departmentModel.getId());
//                int row = i + 3;
//                return Result.error(500, "第" + row + "行单位不存在");
            }

            protectionPointModel.setCreateTime(CommonHelp.getNowTimestamp());
            try {
                protectionPointService.insert(protectionPointModel);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500,"导入失败");
            }
        }
        return Result.success("");
    }

}
